package cn.power.win.win_power.acitivity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.journeyapps.barcodescanner.ViewfinderView;

import java.util.ArrayList;
import java.util.List;

import cn.power.win.win_power.MyApp;
import cn.power.win.win_power.R;
import cn.power.win.win_power.utils.ASUtils;
import cn.power.win.win_power.utils.DeviceBean;
import cn.power.win.win_power.utils.SpUtils;
import cn.power.win.win_power.view.VerificationCodeView;
import me.jessyan.autosize.AutoSizeCompat;
import me.jessyan.autosize.internal.CustomAdapt;

/**
 * Custom Scannner Activity extending from Activity to display a custom layout form scanner view.
 */
public class CustomScannerActivity extends Activity implements
        DecoratedBarcodeView.TorchListener , CustomAdapt {

    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private Button switchFlashlightButton;
    private ViewfinderView viewfinderView;
    private ImageView mIvBack;
    private TextView mZxingStatusView2;
    private VerificationCodeView mVcv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_scanner);



        mVcv = (VerificationCodeView) findViewById(R.id.vcv);
        mVcv.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
                                         @Override
                                         public void onComplete(String content) {
                                             if (content.startsWith("GPRS")) {
                                                 ShowInputPassword(content);
                                             }else if (content.startsWith("RJ45")){
                                                 ShowInputPassword(content);
                                             }

                                           //  Toast.makeText(CustomScannerActivity.this, content, Toast.LENGTH_SHORT).show();
                                             // 发送广播
                                             Intent intent = new Intent("cn.power.win.win_power");
                                             intent.putExtra("data", content);
                                             LocalBroadcastManager.getInstance(CustomScannerActivity.this).sendBroadcast(intent);
                                             //finish();
                                         }
                                     });
        barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.zxing_barcode_scanner);
        barcodeScannerView.setTorchListener(this);

        switchFlashlightButton = (Button) findViewById(R.id.switch_flashlight);

        viewfinderView = (ViewfinderView) findViewById(R.id.zxing_viewfinder_view);
        mZxingStatusView2 = (TextView) findViewById(R.id.zxing_status_view2);
        mZxingStatusView2.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
        //跳转到手动输入界面
          mZxingStatusView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mVcv.setVisibility(View.VISIBLE);

            }
        });

        // if the device does not have flashlight in its camera,
        // then remove the switch flashlight button...
        if (!hasFlash()) {
            switchFlashlightButton.setVisibility(View.GONE);
        }

        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(getIntent(), savedInstanceState);
        capture.decode();

        //changeMaskColor(null);
    }

    private void ShowInputPassword(String content) {
        View contentView = LayoutInflater.from(CustomScannerActivity.this).inflate(R.layout.popupwindow_password, null);
        PopupWindow popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setContentView(contentView);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        //初始化界面
        final EditText etPassword = (EditText) contentView.findViewById(R.id.et_password);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        TextView tvCancel = (TextView) contentView.findViewById(R.id.tv_cancel);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);

        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        // 取消
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                finish();
            }
        });
        // 确认
        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ASUtils.isCanUse(etPassword.getText().toString().trim())) {
                    Toast.makeText(CustomScannerActivity.this,"请先输入密码",Toast.LENGTH_SHORT).show();
                }else {
                    List<String> mPassword = new ArrayList<>();
                    mPassword.add(etPassword.getText().toString().trim());
                    DeviceBean mDeviceBean = new DeviceBean(content,mPassword);
                    // 以mac地址为键值来存取对象
                    SpUtils.putObject(MyApp.context,mDeviceBean.getMac(),mDeviceBean);
                    //取消弹窗
                    popupWindow.dismiss();
                    finish();

                }

            }


        });

        ColorDrawable dw = new ColorDrawable(0x70000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }


    @Override
    protected void onResume() {
        super.onResume();
        capture.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        capture.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        capture.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    /**
     * Check if the device's camera has a Flashlight.
     *
     * @return true if there is Flashlight, otherwise false.
     */
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    public void switchFlashlight(View view) {
        if (getString(R.string.turn_on_flashlight).equals(switchFlashlightButton.getText())) {
            barcodeScannerView.setTorchOn();
        } else {
            barcodeScannerView.setTorchOff();
        }
    }
/*

    public void changeMaskColor(View view) {
        Random rnd = new Random();
        int color = Color.argb(100, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        viewfinderView.setMaskColor(color);
    }
*/

    @Override
    public void onTorchOn() {
        switchFlashlightButton.setText(R.string.turn_off_flashlight);
    }

    @Override
    public void onTorchOff() {
        switchFlashlightButton.setText(R.string.turn_on_flashlight);
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

   /* @Override
    public float getSizeInDp() {
        return 800;
    }*/
   @Override
   public float getSizeInDp() {
       return 480;
   }
    @Override
    public Resources getResources() {
        //需要升级到 v1.1.2 及以上版本才能使用 AutoSizeCompat
      //  AutoSizeCompat.autoConvertDensityOfGlobal((super.getResources()));//如果没有自定义需求用这个方法
        AutoSizeCompat.autoConvertDensity((super.getResources()), 800, false);//如果有自定义需求就用这个方法
        return super.getResources();
    }
}
